"""
商品模型
定义商品、规格、变体相关的数据库模型
"""
from datetime import datetime
import enum
import json
from sqlalchemy.ext.hybrid import hybrid_property
from app.extensions import db

class ProductStatus(enum.Enum):
    """商品状态枚举"""
    DRAFT = 'draft'  # 草稿
    ACTIVE = 'active'  # 上架
    INACTIVE = 'inactive'  # 下架
    DELETED = 'deleted'  # 删除

class Product(db.Model):
    """商品模型"""
    __tablename__ = 'product'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    price = db.Column(db.Numeric(10, 2), nullable=False)
    stock = db.Column(db.Integer, nullable=False, default=0)
    sku = db.Column(db.String(50), unique=True, nullable=False, index=True)
    status = db.Column(db.String(20), nullable=False, default=ProductStatus.DRAFT.value)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    specifications = db.relationship('ProductSpecification', backref='product', lazy='dynamic')
    variants = db.relationship('ProductVariant', backref='product', lazy='dynamic')
    order_items = db.relationship('OrderItem', backref='product', lazy='dynamic')
    inventory_records = db.relationship('InventoryRecord', 
                                       foreign_keys='InventoryRecord.product_id',
                                       backref='product', lazy='dynamic')
    
    def __repr__(self):
        return f'<Product {self.name}>'
    
    def to_dict(self, include_specs=False, include_variants=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'price': float(self.price),
            'stock': self.stock,
            'sku': self.sku,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
        
        if include_specs:
            result['specifications'] = [spec.to_dict() for spec in self.specifications]
        
        if include_variants:
            result['variants'] = [variant.to_dict() for variant in self.variants]
            
        return result

class ProductSpecification(db.Model):
    """商品规格模型"""
    __tablename__ = 'product_specification'
    
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
    name = db.Column(db.String(50), nullable=False)
    _options = db.Column('options', db.Text, nullable=False)
    
    def __repr__(self):
        return f'<ProductSpecification {self.name}>'
    
    @hybrid_property
    def option_list(self):
        """获取选项列表"""
        if self._options:
            return json.loads(self._options)
        return []
    
    @option_list.setter
    def option_list(self, value):
        """设置选项列表"""
        self._options = json.dumps(value)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'options': self.option_list
        }

class ProductVariant(db.Model):
    """商品变体模型"""
    __tablename__ = 'product_variant'
    
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
    sku = db.Column(db.String(50), unique=True, nullable=False, index=True)
    price = db.Column(db.Numeric(10, 2), nullable=False)
    stock = db.Column(db.Integer, nullable=False, default=0)
    _specifications = db.Column('specifications', db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    order_items = db.relationship('OrderItem', backref='variant', lazy='dynamic')
    inventory_records = db.relationship('InventoryRecord', 
                                       foreign_keys='InventoryRecord.variant_id',
                                       backref='variant', lazy='dynamic')
    
    def __repr__(self):
        return f'<ProductVariant {self.sku}>'
    
    @hybrid_property
    def specifications(self):
        """获取规格字典"""
        if self._specifications:
            return json.loads(self._specifications)
        return {}
    
    @specifications.setter
    def specifications(self, value):
        """设置规格字典"""
        self._specifications = json.dumps(value)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'sku': self.sku,
            'price': float(self.price),
            'stock': self.stock,
            'specifications': self.specifications,
            'created_at': self.created_at.isoformat() if self.created_at else None
        } 